package com.olah.user.controller;

import com.olah.common.entity.dto.UtilResponse;
import com.olah.common.entity.dto.request.user.LoginInfo;
import com.olah.common.entity.dto.request.user.RegisterInfo;
import com.olah.common.entity.dto.request.user.SearchUserInfo;
import com.olah.common.entity.po.user.User;
import com.olah.email.Sender;
import com.olah.user.service.BaseService;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Base Information Controller
 */
@RefreshScope
@RestController
@RequestMapping("/user")
public class BaseController {

    @Resource
    private BaseService service;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final Random random = new Random();

    /**
     * 根据 id 查询用户
     * @param targetId 目标用户id
     */
    @GetMapping("/query")
    public UtilResponse<Map<String, Object>> queryById(@RequestParam("targetId") Integer targetId) {
        return UtilResponse.success(service.queryById(targetId));
    }

    /**
     * 根据条件查询用户
     * @param info
     */
    @PostMapping("/query")
    public UtilResponse<List<User>> queryByInfo(@RequestBody SearchUserInfo info) {
        return UtilResponse.success(service.queryByInfo(info));
    }

    /**
     * 用户注册
     * @param registerInfo
     */
    @PostMapping("/register")
    public UtilResponse<Boolean> register(@RequestBody RegisterInfo registerInfo) {
        String key = String.format("regist:email:%s", registerInfo.getEmail());
        String cacheToken = (String) redisTemplate.boundValueOps(key).get();
        if (registerInfo.getToken().equals(cacheToken)) {
            redisTemplate.delete(key);
            service.register(registerInfo);
        } else {
            return UtilResponse.error("验证码错误");
        }
        return UtilResponse.success("注册成功", true);
    }

    /**
     * 用户登录
     * @param loginInfo
     */
    @PostMapping(value = "/login")
    public UtilResponse<User> login(@RequestBody LoginInfo loginInfo) {
        User user = service.login(loginInfo);
        System.out.println(loginInfo);
        System.out.println(user);
        return user == null
            ? UtilResponse.error("登陆失败")
            : UtilResponse.success("登录成功", user);
    }

    /**
     * 获取注册验证码
     * @param email 邮箱地址
     */
    @GetMapping(value = "/token")
    public UtilResponse<Boolean> generateToken(@RequestParam("email") String email) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            builder.append(random.nextInt(10));
        }
        boolean flag = Sender.sendMessage(String.format("你正在注册 Olah 账号, 验证码为：%s, 10分钟内有效", builder), email);
        if (flag) {
            String key = String.format("regist:email:%s", email);
            redisTemplate.boundValueOps(key).set(builder, 10, TimeUnit.MINUTES);
        }
        return flag
            ? UtilResponse.success("验证码已发送至您的邮箱, 请及时查收")
            : UtilResponse.error("当前网络忙, 请稍后再试");
    }

}
